package cn.pugle.base.net.socket.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 客户端。 发送完数据 接收。这里都是阻塞的。
 * Created by tzp on 15-12-7.<br/>
 */
public class MySendReceClient {


    public static void main(String[] args) {
        try (//jdk1.7 try with resource
             Socket socket = new Socket(CONS.inetAddress, CONS.SERVER_PORT);
             OutputStream out = socket.getOutputStream();
             InputStream in = socket.getInputStream();
        ) {
            Thread.sleep(1 * 1000);//先睡5s观察以下
            String me = socket.getLocalAddress().toString();
            System.out.println(me);
            out.write(me.getBytes(CONS.CHARSET_NAME));
            for (String mess : CONS.MESSAGES) {
                System.out.println(mess);
                out.write(mess.getBytes(CONS.CHARSET_NAME));
                Thread.sleep(2 * 1000);
//                Thread.sleep(2 * 1000);
            }
            System.out.println(CONS.PROTOCOL_TAIL + "\n");
            out.write((CONS.PROTOCOL_TAIL + "\n").getBytes(CONS.CHARSET_NAME));

            System.out.println("---------------------------");

            byte[] bytes = new byte[10];
            int count = in.read(bytes);
            while (count != -1) { //xxx 当服务器关闭了socket时, 这里就返回了-1
                System.out.print(new String(bytes, CONS.CHARSET_NAME));
                count = in.read(bytes);
            }

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
